package com.ssh.webssh.controller;

import com.ssh.webssh.pojo.FileDTO;
import com.ssh.webssh.pojo.LoginInfo;
import com.ssh.webssh.pojo.Result;
import com.ssh.webssh.service.WebSSHService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.socket.WebSocketSession;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

@Controller
public class WebSshController {

    @Autowired
    private WebSSHService webSSHService;

    /**
     * 登录页面
     * @return
     */
    @GetMapping("/")
    public String login(){
        return "login";
    }

    /**
     * 主页面
     * @param host
     * @param port
     * @param username
     * @param password
     * @param remember
     * @param model
     * @return
     */
    @PostMapping("/websshpage")
    public String websshpage(@RequestParam("host") String host,
                             @RequestParam("port") String port,
                             @RequestParam("username") String username,
                             @RequestParam("password") String password,
                             @RequestParam(value = "remember" ,required = false) String remember,
                             Model model){
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setHost(host);
        loginInfo.setPort(Integer.parseInt(port));
        loginInfo.setUsername(username);
        loginInfo.setPassword(password);
        loginInfo.setCheck(!StringUtils.isEmpty(remember));
        model.addAttribute("loginInfo",loginInfo);
        return "webssh";
    }

    /**
     * 退出
     * @return
     */
    @GetMapping("/close")
    public String close(HttpSession session) throws Exception{
        webSSHService.disConnect(session);
        return "redirect:";
    }

    /**
     * ftp连接
     * @param session
     * @param host
     * @param port
     * @param username
     * @param password
     * @param remember
     * @return
     * @throws Exception
     */
    @PostMapping("/ftpConnect")
    @ResponseBody
    public Result ftpConnect(HttpSession session,
                           @RequestParam("host") String host,
                           @RequestParam("port") String port,
                           @RequestParam("username") String username,
                           @RequestParam("password") String password,
                           @RequestParam(value = "remember" ,required = false) String remember) throws Exception {
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setHost(host);
        loginInfo.setPort(Integer.parseInt(port));
        loginInfo.setUsername(username);
        loginInfo.setPassword(password);
        loginInfo.setCheck(!StringUtils.isEmpty(remember));
        webSSHService.getFTPConnect(session, loginInfo);
        return Result.ok();
    }

    /**
     * ftp获取文件
     * @param session
     * @param path
     * @return
     * @throws Exception
     */
    @PostMapping("/listFiles")
    @ResponseBody
    public Result<List<FileDTO>> listFiles(HttpSession session, String path) throws Exception {
        return Result.ok(webSSHService.listFiles(session, path));
    }

    /**
     * 上传文件
     * @param session
     * @param file
     * @param targetDir
     * @return
     * @throws Exception
     */
    @PostMapping("/put")
    @ResponseBody
    public Result put(HttpSession session, MultipartFile file, String targetDir) throws Exception {
        webSSHService.put(session, file, targetDir);
        return Result.ok();
    }

    /**
     * 下载单个文件
     * @param fullFileName
     * @param session
     * @param response
     * @throws Exception
     */
    @GetMapping("/down")
    @ResponseBody
    public void down(String fullFileName, HttpSession session, HttpServletResponse response) throws Exception {
        fullFileName = URLDecoder.decode(fullFileName, "UTF-8");
        String fileName = fullFileName.substring(fullFileName.lastIndexOf("/") + 1);
        //设置下载响应头
        response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        InputStream inputStream = webSSHService.down(session,fullFileName); //文件输入流
        ServletOutputStream outputStream = response.getOutputStream(); //输出流
        IOUtils.copyLarge(inputStream,outputStream);
        /*try (BufferedInputStream bis = new BufferedInputStream(inputStream)){
            byte[] buffer = new byte[1024]; //定义一个字节数组,相当于缓存
            int i = bis.read(buffer);
            while(i != -1){
                outputStream.write(buffer);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

    /**
     * 删除非文件夹
     * @param fullFileName
     * @param session
     * @return
     * @throws Exception
     */
    @PostMapping("/deleteSingleFile")
    @ResponseBody
    public Result deleteSingleFile(String fullFileName, HttpSession session) throws Exception {
        webSSHService.deleteSingleFile(session,fullFileName);
        return Result.ok();
    }
}
